﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using DiscoveryLogic.DataServices.DataObjects;
using DiscoveryLogic.DataServices.DataObjects.Entities;

namespace DiscoveryLogic.DataServices.Caches
{
    public abstract class SearchAutoCompleteService<T>:IHttpHandler 
    {
        protected abstract IEnumerable<T> GetCompletionItems(string prefix);
        protected abstract IEnumerable<T> GetCompletionItems(EntityType entityType, string fieldName, string prefix);

        #region Implementation of IHttpHandler

        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler" /> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext" /> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests. </param>
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest request = context.Request;
            string prefix = request.QueryString["prefix"];
            if(string.IsNullOrEmpty(prefix))
            {
                throw new HttpException(400, "Bad request");
            }

            T[] items = null;
            string fieldName = string.Empty;
            if (!string.IsNullOrEmpty(request.QueryString["field_name"]) && 
                !string.IsNullOrEmpty(request.QueryString["entity_type"]))
            {
                fieldName = request.QueryString["field_name"];
                string entity_type = request.QueryString["entity_type"];
                EntityType entityType = (EntityType)Enum.Parse(typeof(EntityType), entity_type);
                items = this.GetCompletionItems(entityType, fieldName, prefix).ToArray();
            }
            else
            {
                items = this.GetCompletionItems(prefix).ToArray();
            }
            JavaScriptSerializer serializer=new JavaScriptSerializer();
            string responseText = serializer.Serialize(items);
            context.Response.ContentType = "text/json";
            context.Response.WriteFile(responseText);
        }

        /// <summary>
        /// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler" /> instance.
        /// </summary>
        /// <returns>
        /// true if the <see cref="T:System.Web.IHttpHandler" /> instance is reusable; otherwise, false.
        /// </returns>
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        #endregion
    }
}
